/**
 * @summary plug
 */
import fs from 'fs';
import logger from 'morgan';
import * as cookieParser from 'cookie-parser';
import * as express from 'express';
import * as path from 'path';
import * as createError from 'http-errors';
import { Express } from 'express-serve-static-core';
import 'express-async-errors';

/**
 * @module router
 */
import RoutesIndex from './src/routes/index';

/**
 * @summary app
 */
class Apps extends RoutesIndex {
    public app: Express;
    constructor() {
        super();
        this.app = express();
        this.expressUse();
    }
    private expressUse() {
        this.app.use(express.json());
        this.app.use(express.urlencoded({ extended: false }));
        this.app.use(cookieParser());
        this.app.use(express.static(path.join(__dirname + '/public')));
        this.routerUse((e: string) => {
            if (e !== 'check routes ok') {
                console.error(e)
                process.exit(1)
            }
            console.log('routes use initialization OK!');
            this.errorsUse();
        }, this.app);
        console.log('express use initialization OK!');
    }
    private errorsUse() {
        // catch 404 and forward to error handler
        this.app.use(function(req: any, res: any, next: any) {
            // res.status(404);
            next(createError(404));
        });

        // catch 401 and forward to error handler
        this.app.use(function(req: any, res: any, next: any) {
            // res.status(401);
            next(createError(401));
        });

        // catch 500 and forward to error handler
        this.app.use(function(req: any, res: any, next: any) {
            // res.status(500);
            next(createError(500));
        });

        // error handler
        this.app.use(function(err: any, req: any, res: any, next: any) {
            console.log(err.message)
            console.log(err.status)
            res.json({
                code: err.status,
                msg: err.message
            })
        });

        console.log('error handler use initialization OK!')
    }
}

export default Apps;